<template>
  <div class="mod-prod prod-list-mod">
    <avue-crud
      ref="crud"
      :page="page"
      :data="dataList"
      :table-loading="dataListLoading"
      :option="tableOption"
      @on-load="getDataList"
      @sort-change="sortChange"
      @search-reset="searchReset"
      @search-change="searchChange"
      @selection-change="selectionChange"
      @refresh-change="refreshChange"
    >

      <template slot-scope="scope" slot="deliveryMode">
        <div>{{scope.row.deliveryMode | DeliveryMode}}</div>
      </template>
      
      <template slot="menuLeft">
        <!-- <el-button type="primary"
                   icon="el-icon-plus"
                   size="small"
                   v-if="isAuth('prod:prod:save')"
        @click.stop="addOrUpdateHandle()">新增</el-button>-->
      </template>
      <template slot-scope="scope" slot="waterSoldNum">
        <el-input
          type="number"
          size="small"
          v-model="scope.row.waterSoldNum"
          onkeypress='return( /[\d]/.test(String.fromCharCode(event.keyCode)))'
          class="sales-volume"
          @blur="handleChange(scope.row.prodId, scope.row.waterSoldNum)"
          :min="0"
          :max="1000000000"
          ></el-input>
      </template>
      <template slot="search">
        <el-col :md="6" :xs="24">
          <el-form-item :label="this.$i18n.t('product.isTop')">
          <el-select v-model="isTop">
            <el-option :label="$t('publics.no')" :value="0"></el-option>
            <el-option :label="$t('publics.yes')" :value="1"></el-option>
          </el-select>
          </el-form-item>
        </el-col>
      </template>
      <!-- 0:商家下架 1:正常 2:平台下架 3:待平台审核 4:审核失败 -1表示删除 -->
      <template slot-scope="scope" slot="status">
        <el-tag v-if="scope.row.status === 1" type="success" size="small">{{
          $t("prodList.onShelf")
        }}</el-tag>
        <el-tag v-else-if="scope.row.status === 0" size="small">{{
          $t("prodList.offShelf")
        }}</el-tag>
        <el-tag v-else-if="scope.row.status === 2" size="small" type="danger">{{
          $t("product.violation")
        }}</el-tag>
        <el-tag
          v-else-if="scope.row.status === 3"
          type="warning"
          size="small"
          >{{ $t("product.pendingReview") }}</el-tag
        >
        <el-tag v-else-if="scope.row.status === 4" type="danger" size="small">{{
          $t("prodList.refusePass")
        }}</el-tag>
        <el-tag v-else size="small">{{ $t("prodList.other") }}</el-tag>
      </template>
      <template slot-scope="scope" slot="isTop">
        <el-tag v-if="scope.row.isTop === 0" size="small">{{$t('publics.no')}}</el-tag>
        <el-tag
          v-else-if="scope.row.isTop === 1"
          size="small"
          type="success"
        >{{$t('publics.yes')}}</el-tag>
      </template>
      <template slot-scope="scope" slot="menu">
        <div class="menu-btn">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="small"
            v-if="isAuth('prod:prod:update')"
            @click="showProdInfo(scope.row.prodId)"
            >{{ $t("prodList.lookOver") }}</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-document-checked"
            size="small"
            v-if="isAuth('prod:prod:update') && scope.row.status > 1"
            @click="auditProdHandle(scope.row)"
            >{{ $t("prodList.offShelfManage") }}</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-bottom"
            size="small"
            v-if="isAuth('prod:prod:update') && scope.row.status < 2"
            @click="offlineProdHandle(scope.row)"
          >
            {{ $t("prodList.offShelfProd") }}
            <el-tooltip
              class="item"
              effect="dark"
              placement="right"
              :content="$t('prodList.content')"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="small"
            v-if="isAuth('prod:prod:delete')"
            @click="deleteHandle(scope.row.prodId)"
            >{{ $t("remindPop.delete") }}</el-button
          >
          <el-button
            type="primary"
            size="small"
            v-if="scope.row.status === 1"
            @click="toTopHandle(scope.row)"
        >{{scope.row.isTop === 1 ? $t('liveRoom.cancelTopping'):$t('publics.isTop')}}</el-button>
        </div>
      </template>
    </avue-crud>
    <!-- 商品审核弹窗 -->
    <!-- <ProdAudit v-if="ProdAuditVisible"
               ref="ProdAudit"
    @refreshDataList="refreshChange"></ProdAudit>-->

    <!-- 商品审核弹窗 -->
    <ProdAudit
      v-if="ProdAuditVisible"
      ref="ProdAudit"
      selectUrl="/prod/prod/getOfflineHandleEventByProdId"
      updateUrl="/prod/prod/prodAudit"
      @refreshDataList="refreshChange"
    ></ProdAudit>

    <!-- 商品详情弹窗 -->
    <el-dialog
      :title="this.$i18n.t('prodList.detailsTitle')"
      :visible.sync="showProdInfoDialog"
      width="70%"
    >
      <div class="prod-row">
        <span class="row-title">{{ $t("product.pic") }}</span>
        <img :src="prodInfo.pic" alt />
      </div>
      <div class="prod-row">
        <span class="row-title">{{ $t("product.prodName") }}</span>
        <span>{{ prodInfo.prodName }}</span>
      </div>
      <div class="prod-row">
        <span class="row-title">{{ $t("prodList.sellingPoints") }}</span>
        <span>{{ prodInfo.brief }}</span>
      </div>
      <div class="prod-row">
        <span class="row-title">{{ $t("prodList.specs") }}</span>
        <!-- 规格表格 -->
        <el-table :data="prodInfo.skuList" border style="width: 100%">
          <el-table-column
            prop="properties"
            :label="this.$i18n.t('prodList.attribute')"
            width="180"
          >
            <template slot-scope="scope">
              <p v-if="scope.row.properties">{{ scope.row.properties }}</p>
              <p v-else>{{ $t("prodList.noAttribute") }}</p>
            </template>
          </el-table-column>
          <el-table-column
            prop="pic"
            :label="this.$i18n.t('product.pic')"
            width="180"
          >
            <template slot-scope="scope">
              <img
                :src="resourcesUrl + scope.row.pic"
                alt
                v-if="scope.row.pic"
              />
              <p v-else>{{ $t("prodList.noPictures") }}</p>
            </template>
          </el-table-column>
          <el-table-column
            prop="prodName"
            :label="this.$i18n.t('product.prodName')"
          ></el-table-column>
          <el-table-column
            prop="price"
            :label="this.$i18n.t('prodList.salesPrice')"
          ></el-table-column>
          <el-table-column
            prop="oriPrice"
            :label="this.$i18n.t('prodList.marketValue')"
          ></el-table-column>
          <el-table-column
            prop="stocks"
            :label="this.$i18n.t('product.totalStocks')"
          ></el-table-column>
          <el-table-column
            prop="weight"
            :label="this.$i18n.t('prodList.prodWeight')"
          ></el-table-column>
          <el-table-column
            prop="volume"
            :label="this.$i18n.t('prodList.prodVolume')"
          ></el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showProdInfoDialog = false">{{
          $t("remindPop.confirm")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { tableOption } from '@/crud/prod/prodList'
import ProdAudit from '@/components/offline-audit'
import i18n from '../../../i18n/i18n'
export default {
  data () {
    return {
      dataForm: {
        prodName: ''
      },
      dataList: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      searchForm: {},
      dataListSelections: [],
      waterSoldNum: '',
      dataListLoading: false,
      tableOption: tableOption,
      resourcesUrl: window.SITE_CONFIG.resourcesUrl,
      showProdInfoDialog: false,
      ProdAuditVisible: false,
      prodName: '',
      prodNameRouter: '',
      // 0无 1.排序号排序
      sortParam: 0,
      isTop: null,
      // 0无 1 正序 2倒序
      sortType: 0,
      prodInfo: {},
      skuList: [],
      waterArr: []
    }
  },
  components: {
    ProdAudit
  },
  created () {
    if (this.$route.query.prodName) {
      this.prodNameRouter = this.$route.query.prodName
    }
  },
  mounted () {
    // 获取平台分类
    this.getCategoryList()
  },
  filters: {
    DeliveryMode: function (value) {
      // 将商品的配送方式字符串转化为json
      let objValue = JSON.parse(value)
      // 声明返回结果 result
      let result = []
      if (objValue.hasCityDelivery === true) {
        result.push(i18n.t('product.sameCityDelivery'))
      }
      if (objValue.hasUserPickUp === true) {
        result.push(i18n.t('product.userPickUp'))
      }
      if (objValue.hasShopDelivery === true) {
        result.push(i18n.t('product.shopDelivery'))
      }
      return result.join(' / ')
    }
  },
  methods: {
    // 获取数据列表
    getDataList (page) {
      this.fdataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/prod/prod/page'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign(
            {
              current: page == null ? this.page.currentPage : page.currentPage,
              prodName: this.prodNameRouter ? this.prodNameRouter : this.prodName,
              size: page == null ? this.page.pageSize : page.pageSize,
              sortParam: this.sortParam,
              sortType: this.sortType,
              isTop: this.isTop
            },
            this.searchForm
          )
        )
      }).then(({ data }) => {
        this.page = page
        this.dataList = data.records
        for (const key in this.dataList) {
          if (this.dataList.hasOwnProperty(key)) {
            const element = this.dataList[key]
            element.imgs = element.imgs.split(',')[0]
          }
        }
        this.prodName = ''
        this.prodNameRouter = null
        this.page.total = data.total
        this.page.currentPage = data.current
        this.dataListLoading = false
      })
    },
    // 获取平台分类列表
    getCategoryList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/prod/category/listCategoryByGrade'),
        method: 'get',
        params: this.$http.adornParams({
          grade: 2
        })
      }).then(({ data }) => {
        this.tableOption.column[9].dicData = data
        this.dataListLoading = false
      })
    },
    // 获取商品详情
    showProdInfo (id) {
      this.showProdInfoDialog = true
      this.$http({
        url: this.$http.adornUrl(`/prod/prod/info/${id}`),
        method: 'GET'
      })
        .then(res => {
          this.prodInfo = res.data
          this.skuList = res.data.skuList
        })
        .catch()
    },
    // 更改注水销量
    handleChange (id, waterSoldNum) {
      waterSoldNum = Math.round(waterSoldNum)
      if (waterSoldNum > 1000000000) {
        waterSoldNum = 1000000000
      }
      this.$http({
        url: this.$http.adornUrl('/prod/prod/waterSoldNum'),
        method: 'put',
        params: {
          waterSoldNum: waterSoldNum,
          prodId: id
        }
      }).then(() => {
        this.$message({
          message: '操作成功',
          type: 'success',
          duration: 1500
        })
        this.getDataList(this.page)
      })
    },
    // 删除
    deleteHandle (id) {
      this.$confirm(this.$i18n.t('remindPop.makeSure') + ' ' + `[${id ? this.$i18n.t('remindPop.delete') : this.$i18n.t('remindPop.batchDeletion')}]` + ' ' + this.$i18n.t('remindPop.operation') + '?', this.$i18n.t('remindPop.remind'), {
        confirmButtonText: this.$i18n.t('remindPop.confirm'),
        cancelButtonText: this.$i18n.t('remindPop.cancel'),
        type: 'warning'
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl(`/prod/prod/${id}`),
            method: 'delete',
            data: this.$http.adornData({})
          }).then(({ data }) => {
            this.$message({
              message: this.$i18n.t('remindPop.succeeded'),
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList(this.page)
              }
            })
          })
        })
        .catch(() => { })
    },
    // 下架
    offlineProdHandle (row) {
      this.$prompt(this.$i18n.t('remindPop.determine') + this.$i18n.t('remindPop.prod') + `[${row.prodName}]` + this.$i18n.t('remindPop.offshelf') + this.$i18n.t('remindPop.reason'), '提示', {
        confirmButtonText: this.$i18n.t('remindPop.confirm'),
        cancelButtonText: this.$i18n.t('remindPop.cancel'),
        inputErrorMessage: this.$i18n.t('remindPop.emptyReason'),
        inputValidator: (value) => {
          if (value === null) {
            return this.$i18n.t('remindPop.emptyReason')
          }
          if (value.trim().length < 1) {
            return this.$i18n.t('remindPop.emptyReason')
          }
        }
      }).then((obj) => {
        this.$http({
          url: this.$http.adornUrl(`/prod/prod/offline`),
          method: 'post',
          data: this.$http.adornData({
            handleId: row.prodId,
            offlineReason: obj.value || null
          })
        }).then(({ data }) => {
          this.$message({
            message: this.$i18n.t('remindPop.succeeded'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.getDataList(this.page)
            }
          })
        })
      })
    },
    // 条件查询
    searchChange (params) {
      this.searchForm = params
      this.page.currentPage = 1
      this.getDataList(this.page)
    },
    toTopHandle (row) {
      var str = this.$i18n.t('publics.isTop')
      if (row.isTop === 1) {
        str = this.$i18n.t('liveRoom.cancelTopping')
      }
      this.$confirm(this.$i18n.t('remindPop.makeSure') + ' ' + str + ' ' + this.$i18n.t('remindPop.operation') + '?', this.$i18n.t('remindPop.remind'), {
        confirmButtonText: this.$i18n.t('remindPop.confirm'),
        cancelButtonText: this.$i18n.t('remindPop.cancel'),
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/prod/prod/toTop/' + row.prodId),
          method: 'put',
          data: this.$http.adornData({})
        }).then(({ data }) => {
          this.$message({
            message: this.$i18n.t('remindPop.succeeded'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.refreshChange()
            }
          })
        })
      }).catch(() => { })
    },
    // 多选变化
    selectionChange (val) {
      this.dataListSelections = val
    },
    // 商品商品审核
    auditProdHandle (row) {
      this.ProdAuditVisible = true
      this.$nextTick(() => {
        this.$refs.ProdAudit.init(row.prodId)
      })
    },
    // 清空自定义数据
    searchReset () {
      this.prodName = ''
      this.isTop = ''
    },
    sortChange (data) {
      console.log(data)
      // 排序字段 0无 1加入时间 2累计客户 3累计邀请 4累计收益
      switch (data.prop) {
        case 'seq': this.sortParam = 1
          break
      }
      // 排序类型 0无 1 正序 2倒序
      switch (data.order) {
        case 'descending': this.sortType = 2
          break
        case 'ascending': this.sortType = 1
          break
        default: this.sortType = 0
          break
      }
      this.getDataList(this.page)
    },
    // 刷新商品
    refreshChange () {
      this.getDataList(this.page)
    }
  }
}
</script>
<style lang="scss">
.mod-prod.prod-list-mod {
  .prod-row {
    margin: 20px 50px;
  }
  .prod-row img {
    width: 150px;
    height: 150px;
  }
  .prod-row .row-title {
    padding-right: 20px;
  }
  .el-table-column {
    text-align: center;
  }
  .operate-btn {
    margin-left: 5px !important;
  }
  /* 注水销量输入框 */
  .sales-volume .el-input__inner {
    padding-left: 8px;
    padding-right: 0;
  }

  // 按钮
  .menu-btn {
    .el-button.el-button--primary.el-button--small,
    .el-button.el-button--danger.el-button--small {
      margin-bottom: 8px;
    }
  }
}
</style>
